package com.pds.web.opsOrganization.controller;

import com.alibaba.excel.EasyExcel;
import com.pds.common.core.controller.BaseController;
import com.pds.common.core.domain.R;
import com.pds.common.core.page.TableDataInfo;
import com.pds.common.utils.poi.ExcelUtil;
import com.pds.web.company.excel.CompanyContactExcel;
import com.pds.web.company.excel.CompanyContactListener;
import com.pds.web.company.excel.CompanyContactTemplate;
import com.pds.web.opsOrganization.service.IOpsOrganizationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 运维机构用户管理
 */
@RestController
@RequestMapping("/opsOrganization")
public class OpsOrganizationUserController extends BaseController {

    @Autowired
    private IOpsOrganizationUserService opsOrganizationUserService;

    /**
     * 运维机构新增用户
     * @param map
     *          - userName 用户名
     *          - phone 手机号
     *          - roleId 角色id
     * @return
     * @throws Exception
     */
    @PostMapping("addUser")
    @PreAuthorize("@ss.hasPermi('ops:user:edit')")
    public R addUser(@RequestBody Map map) throws Exception {
        opsOrganizationUserService.addUser(map);
        return R.ok();
    }

    /**
     * 修改用户
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("updateUser")
    @PreAuthorize("@ss.hasPermi('ops:user:edit')")
    public R updateUser(@RequestBody Map map) throws Exception {
        opsOrganizationUserService.updateUser(map);
        return R.ok();
    }


    /**
     * 下载联系人模板
     * @param response
     */
    @GetMapping("/downContactTemplate")
    public void downContactTemplate(HttpServletResponse response) throws Exception {
        String fileName = URLEncoder.encode("运维机构联系人模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<CompanyContactTemplate> list = new ArrayList<>();
        ExcelUtil<CompanyContactTemplate> excelUtil = new ExcelUtil<>(CompanyContactTemplate.class);
        excelUtil.exportExcel(response, list, "运维机构联系人模板");
    }

    @PostMapping("addUserBatch")
    @PreAuthorize("@ss.hasPermi('ops:user:edit')")
    public R<String> addUserBatch(MultipartFile file) throws Exception {
        //获取文件名+后缀
        String filename = file.getOriginalFilename();
        if (filename != null) {
            //获取其后缀
            String extension = filename.substring(filename.lastIndexOf(".") + 1);
            if (!(extension.equals("xls") || extension.equals("xlsx"))) {
                throw new Exception("文件格式有误,请检查上传文件格式");
            }
        }
        //获取文件的输入流
        InputStream inputStream = file.getInputStream();
        List<CompanyContactExcel> list = EasyExcel.read(inputStream) //调用read方法
                //注册自定义监听器，字段校验可以在监听器内实现
                .registerReadListener(new CompanyContactListener())
                .head(CompanyContactExcel.class) //对应导入的实体类
                .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作
        Integer count = opsOrganizationUserService.addUserBatch(list);
        return R.ok(count + "条人员数据导入成功！");
    }

    /**
     * 查询运维机构用户列表
     * map
     *  - opsId 环保局查询时需要传入id
     *  - userName 姓名
     *  - phone 电话
     *  - idCard 身份证号码
     * @return
     */
    @GetMapping("getUserList")
    public TableDataInfo getOrganizationUserList(@RequestParam Map map) throws Exception {
        startPage();
        List<Map> list = opsOrganizationUserService.getOrganizationUserList(map);
        return getDataTable(list);
    }

    /**
     * 查询运维机构用户详细
     * userId 用户id
     * @return
     */
    @GetMapping("getUserInfo")
    public R getUserInfo(
            @RequestParam("userId")Long userId) throws Exception {
        Map map = opsOrganizationUserService.getUserInfo(userId);
        return R.ok(map);
    }

}
